package services

import (
	"errors"
	"hft/Database/admin"
	"hft/Http/Models/request"
	"hft/e"
	"hft/global"
	"hft/tools"
)

type Base struct{}

func (b *Base) Login(account *request.Login) (token string, err error) {

	var myAccount *admin.Account

	if err := global.OC_DB.Where("username = ?", account.Username).First(&myAccount).Error; err != nil {
		return "", errors.New("账号名称或者密码不正确,请重新输入")
	} else {

		if myAccount.Status == false {
			return "", errors.New("该账号被禁用")
		}

		if myAccount.IsAudit == 1 {
			return "", errors.New("该账号审核中")
		}

		if myAccount.IsAudit == 3 {
			return "", errors.New("该账号审核不通过")
		}

		j := tools.NewJWT() //获取新的秘钥
		var baseClaims = tools.BaseClaims{UserID: myAccount.ID, Username: account.Username, Status: myAccount.Status, RealName: myAccount.RealName}
		var claims = j.CreateClaims(baseClaims, "3h", "1h")
		if token, err := j.CreateToken(claims); err != nil {
			return "", errors.New("授权失败")
		} else {
			return token, nil
		}
	}

}

func (b *Base) PhoneLogin(account *request.Login) (token string, err error) {

	err = tools.AliyunSmsTool.VerifyValid("SMS_", account.Phone, account.Code)

	if err != nil {
		return "", err
	}

	var myAccount *admin.Account

	err = global.OC_DB.Where("phone = ?", account.Phone).First(&myAccount).Error

	if err != nil {
		return "", errors.New("无该账号存在")
	}

	if myAccount.Status == false {
		return "", errors.New("该账号被禁用")
	}

	if myAccount.IsAudit == 1 {
		return "", errors.New("该账号审核中")
	}

	if myAccount.IsAudit == 3 {
		return "", errors.New("该账号审核不通过")
	}

	j := tools.NewJWT() //获取新的秘钥
	var baseClaims = tools.BaseClaims{UserID: myAccount.ID, Username: myAccount.Username, Status: myAccount.Status, RealName: myAccount.RealName}
	var claims = j.CreateClaims(baseClaims, "3h", "1h")
	if token, err := j.CreateToken(claims); err != nil {
		return "", errors.New("授权失败")
	} else {
		return token, nil
	}
}

func (*Base) SendCode(phone string, prefix string) (err error) {

	var model string
	var res = tools.CheckPhoneNumber(phone)
	if res == 0 {
		model = global.OC_CONFIG.AliyunSms.SmsModel
	} else if res == 1 {
		phone = "852" + phone
		model = global.OC_CONFIG.AliyunSms.SmsHKModel
	} else if res == 2 {
		phone = "853" + phone
		model = global.OC_CONFIG.AliyunSms.SmsHKModel
	} else {
		return errors.New(e.PhoneNotRight)
	}

	tools.AliyunSmsTool.SendValid(prefix, phone, model)

	return nil
}

func (*Base) ValidCode(prefix string, phone string, code string) (err error) {

	err = tools.AliyunSmsTool.VerifyValid(prefix, phone, code)

	return

}

var BaseService = new(Base)
